// import"from './index.less'
import './index.css'
import { debounce, throttle } from 'lodash'
import React, { useEffect, useMemo, useRef, useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import { MoreOutline, CloseOutline } from 'antd-mobile-icons'
import { Swiper, NavBar, Space, Card, Tabs, Popup, Button, DotLoading, Stepper, SideBar } from 'antd-mobile'
import axios from '../../util/axios.config'
axios.defaults.baseURL = 'http://47.116.116.42:3000/'
import { useThrottleFn } from 'ahooks'
import { SubmitBar, Badge } from 'react-vant';
import { createFromIconfontCN } from '@react-vant/icons'
import { useDispatch } from 'react-redux'
import { addShop } from '../../redux/shop_reducer'

const IconFont = createFromIconfontCN(
    '//at.alicdn.com/t/c/font_3954496_c8cb486o7s.js'
)




export default function Shop() {
    const dispatch=useDispatch()


    const { id } = useParams()
    const [shopData, setShopData] = useState([])
    const [list, setlist] = useState([])
    const navigate = useNavigate()
    const [clist, setclist] = useState([])
    const allprice = useMemo(() => {
        return clist.reduce((p, c) => p + c.price * c.num, 0)
    })

    const allnum = useMemo(() => {
        return clist.reduce((p, c) => p + c.num, 0)
    })
    const right = (
        <div style={{ fontSize: 24 }}>
            <Space style={{ '--gap': '16px' }}>
                <MoreOutline />
            </Space>
        </div>
    )

    // 根据点击的餐品
    const getShop = async () => {
        const { data: { data } } = await axios.get('/food/sp', {
            params: { id }
        })
        setShopData(data)
        dispatch(addShop(data))
    }

    const getlist = async () => {
        let { data } = await axios.get('/sunt/get-type')
        let data1 = await axios.get('/sunt/get-list')
        setclist(data1.data.filter(item => item.num != 0))
        setlist(data)
    }
    useEffect(() => {
        getlist()
        getShop()
    }, [])




    const Changenum = async (id, num) => {
        await axios.put('/sunt/update-num', { id, num })
        getlist()
    }
    const handeclick = debounce((e, n) => {
        Changenum(n, 1)   // n: id  
        Add(e)
    }, 300)

    const handeclick2 = debounce((n, b) => {
        Changenum(n, b) // b:id   ，b:数量
    }, 300)

    const [activeKey, setActiveKey] = useState('1')
    const { run: handleScroll } = useThrottleFn(
        () => {
            let currentKey = list[0]._id
            for (const item of list) {
                const element = document.getElementById(`anchor-${item._id}`)
                if (!element) continue
                const rect = element.getBoundingClientRect()
                if (rect.top <= 0) {
                    currentKey = item._id
                } else {
                    break
                }
            }
            setActiveKey(currentKey)
        },
        {
            leading: true,
            trailing: true,
            wait: 100,
        }
    )
    const mainElementRef = useRef(null)
    useEffect(() => {
        const mainElement = mainElementRef.current
        if (!mainElement) return
        mainElement.addEventListener('scroll', handleScroll)
        return () => {
            mainElement.removeEventListener('scroll', handleScroll)
        }
    }, [])

    // 小球动画
    const Box = useRef(null)
    const Boxcurl = () => Box.current
    // console.log(Boxcurl());
    let CreateBall = (left, top) => {
        let box = document.createElement('div')
        box.style.position = 'absolute'
        box.style.width = '10px'
        box.style.height = '10px'
        box.style.borderRadius = '50%'
        box.style.left = left + 'px'
        box.style.top = top + 'px'
        box.style.backgroundColor = '#ff6700'
        box.style.transition = 'all 1s  ease'

        document.body.appendChild(box)
        setTimeout(() => {
            box.style.left = Boxcurl().offsetLeft + 'px'
            box.style.top = Boxcurl().offsetTop + 'px'
        }, 0);

        box.ontransitionend = () => {
            box.remove()
        }
    }
    const Add = (e) => {
        let x = e.clientX
        let y = e.clientY
        CreateBall(x, y)
    }


    const a = {
        width: '90%',
        margin: '0 auto',
        height: "inherit",
        boxShadow: "0 0 10px #C1C1C1",
        marginTop: 10

    }
    return (
        <div>

            {shopData && shopData.sid && <div className='pre'>
                <div >
                    <NavBar backArrow onBack={() => navigate('/home')} right={right}>
                        <h4>{shopData.sid.name}</h4>
                    </NavBar>
                </div>

                <Card round style={a}>
                    <div style={{ display: 'flex', margin: '10px 0' }}>店铺名称：<h4>{shopData.sid.name}</h4></div>
                    <div style={{ display: 'flex' }}>商家地址：<h4>{shopData.sid.address}</h4></div>
                </Card>
            </div>
            }

            <Tabs>
                <Tabs.Tab title='点餐' key='fruits'>
                    <div className="container">
                        <div className="side">
                            <SideBar
                                activeKey={activeKey}
                                onChange={key => {
                                    document.getElementById(`anchor-${key}`)?.scrollIntoView()
                                }}
                            >
                                {list.map(item => (
                                    <SideBar.Item key={item._id} title={item.name} />
                                ))}
                            </SideBar>
                        </div>
                        <div className="main" ref={mainElementRef}>
                            {list.map(item => (
                                <div key={item._id}>
                                    <h2 id={`anchor-${item._id}`}>{item.name}</h2>
                                    {
                                        item.text.map(item1 => {
                                            return (
                                                < div className="food-item" key={item1._id} >
                                                    <img src={'/imgs/' + item1.path + '.jpg'} alt="" />
                                                    <div style={{
                                                        display: 'flex',
                                                        flexDirection: 'column',
                                                        justifyContent: 'space-between',
                                                    }}>
                                                        <h4>{item1.name}</h4>
                                                        <p>月销888  好评率100%</p>
                                                        <p style={{ color: 'red' }}>￥{item1.price}</p>
                                                    </div>
                                                    <div style={{}}>
                                                        {
                                                            item1.num == 0 ? <button
                                                                // onClick={(e) => {
                                                                //     Changenum(item1._id, 1)
                                                                //     Add(e)
                                                                // }}
                                                                onClick={(e) => {
                                                                    handeclick(e, item1._id)
                                                                }}
                                                                style={{ width: '20px' }}>+</button> :
                                                                <Stepper
                                                                    min={0}
                                                                    style={{
                                                                        fontSize: '12px', width: '100px',
                                                                    }}
                                                                    defaultValue={item1.num}
                                                                    onChange={(value) => {
                                                                        handeclick2(item1._id, value)
                                                                    }}
                                                                />
                                                        }
                                                    </div>
                                                </div>
                                            )
                                        })
                                    }
                                </div>
                            ))}
                        </div>
                    </div>
                    <div className="demo-submit-bar" ref={Box}>
                        <SubmitBar
                            onSubmit={() => {
                                navigate('/courier', {
                                    state: {
                                        clist: clist,
                                        shopData: shopData.sid,
                                        allnum,
                                        allprice

                                    }
                                })
                            }}
                            disabled={clist.length === 0 ? true : false}
                            price={allprice * 100}
                            buttonText="去结算"
                        >
                            <Badge content={allnum}>
                                <div>
                                    <IconFont name='icon-gouwuchekong' style={{ fontSize: '40px' }} />
                                </div>

                            </Badge>
                        </SubmitBar>
                    </div>
                </Tabs.Tab>
                <Tabs.Tab title='评价' key='vegetables'>

                </Tabs.Tab>

            </Tabs>

        </div >
    )
}
